package com.ddone.code.executor.task;

import com.ddone.code.executor.controller.MyWebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@EnableScheduling
public class TimeTask {

    private static final Logger logger = LoggerFactory.getLogger(TimeTask.class);

    @Scheduled(cron = "0/1 * * * * ?")
    public void test() {
        // System.err.println("********* 定时任务执行 **************");

        CopyOnWriteArraySet<MyWebSocket> webSocketSet = MyWebSocket.getWebSocketSet();

        String message = "定时发送: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        webSocketSet.forEach(c -> {
            try {
                c.sendMessage(message);
            } catch (IOException e) {
                logger.error("Error sending message to WebSocket client", e);
            }
        });

        // System.err.println("定时任务完成.......");
    }
}
